package mplayer.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.Gson;

import mplayer.dao.UserDao;
import mplayer.entity.User;

/**
 * Servlet implementation class ManageUsers
 */
@WebServlet("/ManageUsers")
public class ManageUsers extends HttpServlet {
	private static final long serialVersionUID = 1L;
    Logger logger = LoggerFactory.getLogger(this.getClass());

	private String password;
	private String login;
	private Integer id;
	private Integer rows = 20;
	private Integer page = 1;
	
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ManageUsers() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		UserDao userDao = new  UserDao();
		String operationType = request.getParameter("oper");
		
		//Operation options
		if(validateOperation(operationType)){
			login = request.getParameter("login");
			password = request.getParameter("password");
			password=Utility.convertToMD5(password);
			User user =  new User(login, password);
			
			if(operationType.equals("add")){
				
				userDao.addUser(user);
			}else if(operationType.equals("del")){
				id = Integer.parseInt(request.getParameter("id"));
				userDao.delteUserBuId(id);
			}else if(operationType.equals("edit")){
				id = Integer.parseInt(request.getParameter("id"));
				user.setId(id);
				userDao.updateUser(user);
			}
		}
		
		try{
			rows = Integer.parseInt(request.getParameter("rows"));	
		}catch(NumberFormatException e){
			logger.warn("unknown rows limit parameter");
		}			

		try{
			page = Integer.parseInt(request.getParameter("page"));	
		}catch(NumberFormatException e){
			logger.warn("unknown parameter : page");
		}

		Integer firstResult = rows*page - rows;
        
		jqGridResponse jsonElement = new jqGridResponse();
		
		
		//Search options
		User user = null;
		String searchFlag = request.getParameter("_search");
		if("true".equals(searchFlag)){
			login = request.getParameter("login");
			String idString = request.getParameter("id");
			if(idString != null){
				id = Integer.parseInt(idString);
			}
			user = new User(id,login,password);			
		}

		List<User> list= userDao.getUsers(rows,firstResult,user);
		float number=  (float) userDao.getResultsCount()/ (float) rows;
		Long numberOfpages= (long) Math.ceil(number);
		
		
		/* Remplir la reponse */
		jsonElement.setRows(list);
		jsonElement.setTotal(numberOfpages);
		jsonElement.setRecords(userDao.getResultsCount());
        
		PrintWriter out = response.getWriter();
		Gson gson = new Gson();
		response.setContentType("application/json");
		out.print(gson.toJson(jsonElement));
	}

	/**
	 * Function used to validate the user operation, the operation must be 'add','edit' or 'del' 
	 * */
	
	private boolean validateOperation(String operationType) {
		if (operationType != null) {
			if(operationType.equals("add") || operationType.equals("edit") || operationType.equals("del")){
				logger.debug("Setted operation ["+operationType+"]");
				return true;
			}else {
				logger.debug("Unknown on not implemented operation");
				return false;
			}
		}else {
			logger.debug("Operation is not set");
		}
		return false;
	}

}
